'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
	async reg() {
		const { ctx, app } = this;
		const { username, password, repassword } = ctx.request.body;

		ctx.validate({
			username: {
				type: 'string',
				required: true,
				range: {
					min: 6,
					max: 20
				},
				decs: '用户名'
			},
			password: {
				type: 'string',
				range: {
					min: 6,
					max: 20
				},
				required: true,
				desc: '密码'
			},
			repassword: {
				type: 'string',
				range: {
					min: 6,
					max: 20
				},
				required: true,
				desc: '确认密码'
			}
		});

		if (password !== repassword) {
			ctx.throw(400, '密码和确认密码不一致!');
		}
		if (await app.model.User.findOne({ where: { username } })) {
			ctx.throw(400, '用户已存在!');
		}

		let user = await app.model.User.create({
			username,
			password
		});

		if (!user) {
			ctx.Fail('创建用户失败');
		}

		ctx.Success({ ...user.dataValues, password: null });
	}
	async login() {
		const { ctx, app, service } = this;

		ctx.validate({
			username: {
				type: 'string',
				required: true,
				range: {
					min: 6,
					max: 20
				},
				decs: '用户名'
			},
			password: {
				type: 'string',
				range: {
					min: 6,
					max: 20
				},
				required: true,
				desc: '密码'
			}
		});
		const { username, password } = ctx.request.body;
		// 查询用户存在并且状态可用
		let user = await app.model.User.findOne({ where: { username } });
		if (!user) {
			ctx.throw(400, '用户不存在!');
		}
		user = JSON.parse(JSON.stringify(user));
		// 验证密码
		if (!(await ctx.checkPassword(password, user.password))) {
			ctx.throw(400, '密码错误!');
		}
		delete user.password;
		// 生成token
		user.token = await ctx.getToken(user);

		// 加入缓存
		if (!(await service.redis.set('user_' + user.id, user.token))) {
			ctx.throw(400, '登录失败');
		}

		ctx.Success(user);
	}
	async logout() {
		const { ctx, service } = this;
		// 拿到当前用户ID
		const user_id = ctx.authUser.id;
		// 移除当前用户登录
		if (!(await service.redis.remove('user_' + user_id))) {
			ctx.throw(400, '服务错误,稍后重试！');
		}
		ctx.Success('退出成功!');
	}
	async getSize() {
		const currentUser = this.ctx.authUser;
		return this.ctx.Success({
			total_size: currentUser.total_size,
			used_size: currentUser.used_size
		});
	}
}

module.exports = UserController;
